package pub.cleangao.codegen.enquiry.mysql;

import org.apache.commons.lang3.StringUtils;
import pub.cleangao.codegen.GenConfigHolder;
import pub.cleangao.codegen.enquiry.ColumnEnquiry;
import pub.cleangao.codegen.enquiry.ColumnInfo;
import pub.cleangao.codegen.enquiry.JavaColumnInfo;
import pub.cleangao.codegen.enquiry.TypeFormatter;
import pub.cleangao.codegen.util.ClassField;
import java.util.Map;
import java.util.Set;




public class MySQLColumnEnquiry extends ColumnEnquiry {

    private static final TypeFormatter TYPE_FORMATTER = new MySQLTypeFormatter();
    private static final String SHOW_SQL =
            """
             SELECT  COLUMN_NAME AS 'Field',  COLUMN_DEFAULT AS 'Default',  IS_NULLABLE AS 'Null',  DATA_TYPE AS 'DataType',  CASE DATA_TYPE      WHEN 'int' THEN NUMERIC_PRECISION      WHEN 'varchar' THEN CHARACTER_MAXIMUM_LENGTH  END AS 'MaxLength',  IFNULL(NUMERIC_SCALE,0) AS 'Scale',  COLUMN_TYPE AS 'Type',  COLUMN_KEY 'KEY',  EXTRA AS 'Extra',  COLUMN_COMMENT AS 'Comment'  FROM information_schema.`COLUMNS`  WHERE 1=1 AND TABLE_SCHEMA = '%s' AND TABLE_NAME = '%s' ORDER BY `ORDINAL_POSITION`
            """;


    public MySQLColumnEnquiry(GenConfigHolder config) {
        super(config);
    }

    @Override
    protected String getColumnInfoSql(String tableName) {
        return String.format(SHOW_SQL, config.getDbName(), tableName);
    }

    /*
     * {FIELD=username, EXTRA=, COMMENT=用户名, COLLATION=utf8_general_ci, PRIVILEGES=select,insert,update,references, KEY=PRI, NULL=NO, DEFAULT=null, TYPE=varchar(20)}
     */
    @Override
    protected ColumnInfo buildColumnInfo(Map<String, Object> rowMap){
        Set<String> columnSet = rowMap.keySet();
        for (String columnInfo : columnSet) {
            rowMap.put(columnInfo.toUpperCase(), rowMap.get(columnInfo));
        }
        ColumnInfo columnInfo = new JavaColumnInfo();

        columnInfo.setColumnName(ClassField.convertString(rowMap.get("FIELD")));
        boolean isIdentity = "auto_increment".equalsIgnoreCase(ClassField.convertString(rowMap.get("EXTRA")));
        columnInfo.setIsIdentity(isIdentity);
        boolean isPk = "PRI".equalsIgnoreCase(ClassField.convertString(rowMap.get("KEY")));
        columnInfo.setIsPk(isPk);
        String type = ClassField.convertString(rowMap.get("TYPE"));
        columnInfo.setType(TYPE_FORMATTER.format(type));

        columnInfo.setComment(ClassField.convertString(rowMap.get("COMMENT")));

        String maxLength = ClassField.convertString(rowMap.get("MAXLENGTH"));
        columnInfo.setMaxLength(Integer.valueOf(StringUtils.isEmpty(maxLength) ? "0" : maxLength));

        String scale = ClassField.convertString(rowMap.get("SCALE"));
        columnInfo.setScale(Integer.valueOf(StringUtils.isEmpty(scale) ? "0" : scale));

        String isNullable = ClassField.convertString(rowMap.get("NULL"));
        columnInfo.setIsNullable("YES".equalsIgnoreCase(isNullable));

        return columnInfo;
    }


}
